import datetime

import jwt
from django.contrib.auth.hashers import check_password
from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import render

from rest_framework.response import Response
from rest_framework.views import APIView

from HYDPro_h2002a.settings import EMAIL_HOST_USER, SECRET_KEY
from userapp.sers import *


class UserView(APIView):
    def post(self, request):
        # 创建序列号器  传入数据
        ser = UserSer(data=request.data)
        # 验证数据
        if ser.is_valid():
            user = ser.save()

            # 发送一个激活邮件，让用户去激活

            send_mail(subject="京东集团激活邮件", message="", from_email=EMAIL_HOST_USER,
                      recipient_list=[request.data.get('email')], html_message="恭喜你，已经被我京东录取了,请完成进一步的激活"
                                                                               "<a href='http://127.0.0.1:8000/active?id=%d'>详情</a><br>"
                                                                               "<a href='http://127.0.0.1:8080/#/login'>去登陆</a>" % user.id)
            return Response({'msg': '注册成功', 'status': 200})

        else:
            print(ser.errors)  # 输出报错的地方
            return Response({'msg': '注册失败', 'errors': ser.errors, 'status': 400})  # 如果注册失败，把错误返回给前端


class RegisterView(APIView):
    def get(self, request):
        # 获取 传递来的 用户名
        username = request.GET.get('username')

        # 去数据库查询 是否存在
        if User.objects.filter(username=username):
            return Response({'msg': '该用户名已使用', 'status': 400})
        return Response({'msg': '用户名可用', 'status': 200})


def active_user(request):
    # 激活的本意，就是修改用户的状态
    id = request.GET.get('id')
    User.objects.filter(id=id).update(level=2)
    return HttpResponse('激活成功')


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if user and check_password(password, user.password):
            payload = {
                # exp 表示到期时间
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=1),     #开始令牌时间最长为1分钟，
                'data': {
                    # 自定义 个人存放信息
                    'uid': user.id,
                    'username': user.username,
                    'password': user.password
                }
            }
            key = jwt.encode(payload, SECRET_KEY)  # 编码，包含元素载荷，和settings自带的密钥
            return Response({'msg': '登录成功', 'status': 200, 'token': key,'uid':user.id})
        return Response({'msg': '登录失败', 'status': 400})


class TestTokenView(APIView):
    def get(self, request):

        token = request.GET.get('token')
        print('11111111111111111111111111111111111111')
        print(token)
        try:
            data = jwt.decode(token, SECRET_KEY, verify=True)  # 验证 令牌
            print('22222222222222222222222222')
            print(data)
        except Exception as e:
            return Response({'msg': '令牌有问题'})
        else:
            uid = data.get('data').get('uid')       #获取解码后的uid
            print('3333333333333333333333333333')
            print('uid:', uid)
            user = User.objects.get(id=uid)           #通过uid判断用户的信息
            return Response({'msg': '%s已经登录了' % user.username})       #输入用户名登录

